package com.yjd.back.interceptor;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.yjd.comm.system.dto.AdminDataWrap;
import com.yjd.comm.system.util.AdminDataUtil;
import com.yjd.comm.util.FrameUtil;
import com.yjd.comm.util.ServletUtil;
import com.yjd.comm.util.TxtFileCacheUtil;

/**
 * @ClassName: AccessInterceptor
 * @Description: 权限控制验证
 * @author ready likun_557@163.com
 * @date 2014-8-19 下午2:16:45
 */
public class AccessInterceptor extends HandlerInterceptorAdapter {

	private static String NO_ACCESS_URL_FILE = "noaccessurl.txt";

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		if (urlIsNeedValidate(ServletUtil
				.getRquestUriNotContainContextPath(request))) {
			// 将用户关联的权限菜单编码放入到request中
			AdminDataWrap adminDataWrap = AdminDataUtil.getAdminDataWrap(
					request, response);
			/*List<String> allUrlPattern = sysUserDataWrap.getAllUrlPattern();
			if (allUrlPattern.contains(requestUrl)) {
				List<String> urlPattern = sysUserDataWrap.getUserUrlPattern();
				for (String string : urlPattern) {
					if (requestUrl.startsWith(string)) {
						return true;
					}
				}
				// 无权访问，抛出无权访问异常
				FrameUtil.throwBaseException3(ResultEnum.NOPERMISSION, null,
						"没有权限访问");
				return false;
			}*/
		}
		return true;
	}

	/**
	 * @Title: urlIsNeedValidate
	 * @Description: 判断url是否需要验证
	 * @param @param requestUrl
	 * @param @return 设定文件
	 * @return boolean 返回类型
	 * @throws
	 */
	private boolean urlIsNeedValidate(String requestUrl) {
		List<String> list = TxtFileCacheUtil.get(NO_ACCESS_URL_FILE);
		if (list != null) {
			for (String string : list) {
				if (string != null && string.trim().equals(requestUrl)) {
					return false;
				}
			}
		}
		return true;
	}

	public static void main(String[] args) {
		System.out.println(FrameUtil.json(TxtFileCacheUtil
				.get(NO_ACCESS_URL_FILE)));
	}

}
